#!/usr/bin/python
# -*- coding: utf8 -*-
from pymylib.lib.base import *
from pymylib.model import Session, BiblioType
from pylons.templating import render, render_response
from __init__ import perPage

class BibliotypeController(BaseController):
    template_prefix = '/biblioType'
    template_err_prefix = '/error'

    requires_auth = ['index']    

    def __before__(self):
        if 'user' in session:
            if session['user'] == 'anonymous':
                session['path_before_login'] = request.path_info
                session.save()
                return redirect_to(h.url_for(controller='login'))
        else: return redirect_to(h.url_for(controller='login'))
        
    def __check_permitions__(self):
        """Check for permitions"""

        # Зарегистрирован-ли пользователь в системе?
        if self.requires_auth and session['user'] == 'anonymous':
            c.error = "Необходимо выполнить вход в систему!"
            return False
        
        if session['librarianUser'] or session['adminAccess']:
            return True
        else: c.error = "Нет прав на выполнение этой операции!"


    def index(self):
        redirect_to(action='list')

    def list(self):                
        #model.Biblio._connection.debug = True
        c.pageTitle = unicode('Классификатор типов номенклатуры', encoding='utf8')
        c.formCaption = c.pageTitle

        c.curPage = 0
        try:
            btype_q = Session.query(BiblioType)
            c.curPage = int(request.params['pg'])-1
            c.biblioType = list(btype_q.all()[perPage*c.curPage:perPage*(c.curPage+1)])
        except:
            c.biblioType = list(btype_q.limit(perPage))

        # Получим страницы с диапазоном заданным perPage 
        c.pages = []
        i = 0
        for bib in c.biblioType[:int(btype_q.count()/perPage)+1]:
            i = i+1
            c.pages.append(i)

        if len(c.pages) == 1:
            c.pages = None

        # Сдесь получаем данные о конкретном пользователе
        c.currentUser = None
        c.user_id = session['user_id']
        c.user_name = session['fio']
            
        return render_response(self.template_prefix + '/list.myt')

    def fullview(self, id):
        btype_q = Session.query(BiblioType)
        c.biblioType = btype_q.get_by(id=id)
               
        return render_response(self.template_prefix + '/fullinfo.myt')


    def edit(self, id):

        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')

        btype_q = Session.query(BiblioType)
        c.biblioType = btype_q.get_by(id=id)

        return render_response(self.template_prefix + '/edit.myt')

    def update(self, id):

        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')

        btype_q = Session.query(BiblioType)
        biblioType = btype_q.get_by(id=id)

        if request.params['name'] == "": raise
        else: biblioType.name = request.params['name']

        if request.params['note'] == "": biblioType.note = None
        else: biblioType.note = request.params['note']

        try:
            Session.commit()
        except:
            Session.rollback()
            raise
        
        redirect_to('../list')
        
    def add(self):
        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'add'
            return render(self.template_err_prefix + '/error.mako')

        c.biblioType = None

        return render_response(self.template_prefix + '/edit.myt')

    def create(self):

        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'add'
            return render(self.template_err_prefix + '/error.mako')

        new_btype = BiblioType()
        if request.params['name'] == "": raise
        else: new_btype.name = request.params['name']

        if request.params['note'] == "": new_btype.note = None
        else: new_btype.note = request.params['note']

        try:
            Session.save(new_btype)
            Session.commit()
        except:
            Session.rollback()
            raise
        
        redirect_to('list')

    def delete(self, id):

        # Проверка прав на выполнение данного действия
        if self.__check_permitions__() != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')

        btype_q = Session.query(BiblioType)
        btype_obj = btype_q.get_by(id=id)

        try:
            Session.delete(btype_obj)
            Session.commit()
        except:
            Session.rollback()
            raise

        redirect_to('../list')
